from pyeasyaccept.commom.Configuration import Configuration
from pyeasyaccept.result.Result import Result

class EqualFilesCommand:
    """
    Test if two files are equals.
    The Equal Files command syntax is: 'equalfiles <file1> <file2>'
    
    @author: Magno Jefferson
    """
    
    def execute(self, script, parsedLine):
        """
        This method executes the Equal Files command
        """        
        if(parsedLine.getNumberOfParameters() != 3):
            raise Exception("Equal Files command syntax is: 'equalfiles <file1> <file2>'")
       
        file1 = parsedLine.getParameter(1)
        file2 = parsedLine.getParameter(2)
        
        filesAreEqualsMessage = self.equalFiles(file1, file2)
        if(filesAreEqualsMessage == Configuration.SUCCESS_CODE):
            return Result(parsedLine, Configuration.SUCCESS_CODE, filesAreEqualsMessage)
        
        result = Result(parsedLine, Configuration.ERROR_CODE, filesAreEqualsMessage)
        result.addException(None, filesAreEqualsMessage)
        return result
    
    
    def equalFiles(self, file1, file2):
        """
        This method compare two files.
        @return: The string code 'PASSED' if the files are equals. Otherwise returns the string code "FAILURE"
        """        
        openedFile1 = open(file1, 'r')
        openedFile2 = open(file2, 'r')
        
        file1Lines = openedFile1.readlines()
        file2Lines = openedFile2.readlines()
        
        i = 0
        hasError = False
        while (i < len(file1Lines) and  (not hasError)):
            if (file1Lines[i] != file2Lines[i]):
                hasError = True
                return "The files are different at line number " + str(i+1) +". The expected line content is: " + str(file1Lines[i]).strip()
            else: 
                i = i + 1
                
        return Configuration.SUCCESS_CODE
    
    def getParametersNames(self):
        return ["file1", "file2"]    